
package com.vanda.db.tag;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.commons.beanutils.PropertyUtils;

import com.vanda.db.exception.ParseException;
import com.vanda.db.util.XMLParser;

/**
 * 标签工厂类<br>
 * 
 * @author 王瑛<br>
 * @version Version 1.00<br>
 */
public class TagFactory {
	/** 标签类Class名 */
	private static String TAG_CLASS = null;
	static {
		String clsName = TagFactory.class.getName();
		int index = clsName.lastIndexOf(".");
		TAG_CLASS = clsName.substring(0,index+1);
		
	}
	
	
	/**
	 * 返回标签类实例
	 * @param tagHead 标签头,例如：<logic:empty property="a.b">
	 * @return tagHead对应的标签
	 */
	public static Tag getInstance(String tagHead) throws Exception{

		
		String tagName = XMLParser.getTagName(tagHead);
		
		//取得Tag实例
		Tag tag = getTag(tagName);
		
		//取得tag的属性名称
		HashMap attributes = XMLParser.getTagAttributes(tagHead);
		Iterator iter = attributes.keySet().iterator();
		while(iter.hasNext()){
			String key = (String)iter.next();
			String value = (String)attributes.get(key);
			
			//设置tag属性值，即相当于tag.setKey(value)
			try{
				PropertyUtils.setProperty(tag,key,value);
			}catch(NoSuchMethodException e){
				throw new ParseException("Tag["+tagName+"] : Unknown property '"+key+"'");
			}
			
		}
		
		return tag;
	}
	
	/**
	 * 根据标签名称返回对应的标签类
	 * @param name 标签名称，logic
	 * @return 
	 * @throws Exception
	 */
	private static Tag getTag(String name) throws Exception{
		String prefix = name.substring(0,1).toUpperCase();
		name = TAG_CLASS+prefix+name.substring(1)+"Tag";
		
		Tag tag = (Tag)Class.forName(name).newInstance();
		
		return tag;
	}
}
